# coding: utf-8

from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from garetjax.history.models import ReversionedRevisioned as Revisioned
from garetjax.db.models import GroupedOrderedModel

class Page(Revisioned, GroupedOrderedModel):
    group_by = 'parent'
    
    page_url = models.CharField(_('URL'), max_length=100, blank=True, db_index=True)
    url = models.CharField(max_length=200, editable=False, unique=True)
    parent = models.ForeignKey('self', verbose_name=_('parent'), null=True, blank=True, related_name='subpages')
    title = models.CharField(_('title'), max_length=100)
    content = models.TextField(_('content'), blank=True)
    is_public = models.BooleanField(_('public'), default=True, help_text='Indica se la pagina è visibile a tutti o meno.')
    template_name = models.CharField(_('template'), max_length=70, blank=True)
    
    def __unicode__(self):
        return self.title
    
    def path(self, separator=' › '):
        if self.parent:
            return self.parent.title + separator + self.title
        
        return self.title
    
    def save(self):
        import os
        
        self.page_url = slugify(self.page_url)
        
        if self.parent:
            self.url = os.path.join(self.parent.url, self.page_url.lstrip('/'), '')
        else:
            if self.page_url not in ('', '/'):
                self.url = '/%s/' % self.page_url.strip('/')
            else:
                self.page_url = '/'
                self.url = '/'
        
        super(self.__class__, self).save()
    
    def page_link(self, text=None):
        if text is None:
            text = _('Show on the website')
        return '<a href="%s">%s</a>' % (self.get_absolute_url(), text)
    page_link.allow_tags = True
    page_link.short_description = 'Link'
    
    def get_absolute_url(self):
        return self.url
    
    